/**
 * Copyright (c) 2009, http://www.softwareinlife.com. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided that 
 * the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the http://www.softwareinlife.com nor the names of its 
 *    contributors may be used to endorse or promote products derived from 
 *    this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE SOFTWAREINLIFE AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.softwareinlife.vision.android.ux.vision;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.softwareinlife.vision.android.R;
import com.softwareinlife.vision.android.data.dao.VisionDAO;
import com.softwareinlife.vision.android.data.exceptions.DatabaseConnectionException;
import com.softwareinlife.vision.android.data.exceptions.VisionReadException;
import com.softwareinlife.vision.android.data.exceptions.VisionUpdateException;
import com.softwareinlife.vision.android.data.model.VisionModel;
import com.softwareinlife.vision.android.ux.UXConstants;
import com.softwareinlife.vision.android.ux.plan.CreatePlanActivity;
import com.softwareinlife.vision.android.ux.plan.ReadPlanActivity;
import com.softwareinlife.vision.android.ux.start.VisionSoftwareMenuActivity;
import com.softwareinlife.vision.android.ux.util.ColorUtility;
import com.softwareinlife.vision.android.ux.util.SharedPreferenceUtility;

public class ReadVisionActivity extends Activity {

	/**
	 * Vision List
	 */
	private List<VisionModel> list = null;

	/**
	 * Vision List Layout
	 */
	private LinearLayout visionListLinearLayout = null;

	/**
	 * Vision DAO
	 */
	private VisionDAO dao = null;

	/**
	 * Menu Dialog
	 */
	private Dialog menuDialog = null;

	/**
	 * Selected ID
	 */
	private int selectedIds = 0;

	/**
	 * Selected Menu
	 */
	private int seletedMenu = -1;
	
	/**
	 * On Create
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Content View
		setContentView(R.layout.vision_read);

		// Initialize Members
		initMemebers();

		// Load Data
		loadData();

		// Draw List
		drawData();
	}

	/**
	 * Init Members
	 */
	private void initMemebers() {
		// Create DAO
		try {
			dao = new VisionDAO(this);
		} catch (DatabaseConnectionException e) {
			e.printStackTrace();
		}

		// Get Vision List
		visionListLinearLayout = (LinearLayout) findViewById(R.id.visionListLinearLayout);
	}

	/**
	 * Draw List
	 */
	private void drawData() {
		// Layout Parameters
		LinearLayout.LayoutParams visionRowLinearLayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		visionRowLinearLayoutParams.setMargins(5, 2, 5, 2);

		for (int i = 0; i < list.size(); i++) {
			VisionModel vision = list.get(i);

			// Date Check
			if (vision != null
					&& (vision.getTitle() != null && vision.getTitle().length() > 0)
					&& (vision.getStatement() != null && vision.getStatement()
							.length() > 0)) {

				// Create Row //////////////////////////////////////////////
				LinearLayout visionRowLinearLayout = new LinearLayout(
						getApplicationContext());
				visionRowLinearLayout.setId(vision.getIds());
				visionRowLinearLayout.setClickable(true);
				visionRowLinearLayout.setGravity(Gravity.CENTER);
				visionRowLinearLayout
						.setLayoutParams(visionRowLinearLayoutParams);
				visionRowLinearLayout.setBackgroundColor(R.color.list_color);
				visionRowLinearLayout.setClickable(true);

				// Row Event
				visionRowLinearLayout.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						System.out.println("Vision ID is " + v.getId());
						
						showDialog(v.getId());
					}
				});

				// Blueprint(number + background color)
				TextView blueprintTextView = new TextView(
						getApplicationContext());
				blueprintTextView.setText("" + vision.getIds());
				blueprintTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f);
				blueprintTextView.setWidth(40);
				blueprintTextView.setHeight(40);
				blueprintTextView.setBackgroundResource(ColorUtility
						.getColorCode(vision.getBlueprint()));
				blueprintTextView.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);

				// Add View //////////////////////////////////////////////
				visionRowLinearLayout.addView(blueprintTextView);

				LinearLayout visionContentLinearLayout = new LinearLayout(
						getApplicationContext());
				visionContentLinearLayout.setId(vision.getIds());
				visionContentLinearLayout.setClickable(true);
				visionContentLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
				visionContentLinearLayout
						.setLayoutParams(visionRowLinearLayoutParams);
				visionContentLinearLayout.setOrientation(LinearLayout.VERTICAL);
				visionContentLinearLayout
						.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								System.out.println("Vision ID is " + v.getId());
								showDialog(v.getId());
							}
						});

				// Vision Title Text View
				TextView titleTextView = new TextView(getApplicationContext());
				titleTextView.setText(vision.getTitle());
				titleTextView.setTextSize(15);
				titleTextView.setBackgroundResource(R.color.string_color);
				titleTextView.setTextColor(R.color.button_color1);
				titleTextView.setPadding(2, 0, 2, 0);

				// Add View
				visionContentLinearLayout.addView(titleTextView);

				// Vision Statement Text View
				TextView statementTextView = new TextView(
						getApplicationContext());
				statementTextView.setText(vision.getStatement());
				statementTextView.setTextSize(12);
				statementTextView.setBackgroundResource(R.color.string_color);
				statementTextView.setPadding(2, 0, 2, 0);

				// Add View //////////////////////////////////////////////
				visionContentLinearLayout.addView(statementTextView);

				// Add View
				visionRowLinearLayout.addView(visionContentLinearLayout);

				// Add View
				visionListLinearLayout.addView(visionRowLinearLayout);

				Log.d("Vision", vision.getTitle());
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		// Initialize
		menuDialog = null;
		selectedIds = id;

		VisionModel vision = dao.read(id);
		Log.d("Vision", vision.getTitle());
		Log.d("Vision", vision.getStatement());

		// Create Builer
		Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(vision.getTitle());

		// Create Items
		builder.setSingleChoiceItems(R.array.vision_alert_menu_array, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Log.d("Select", "" + which);
						seletedMenu = which;
					}
				});

		// Create OK
		builder.setPositiveButton(R.string.common_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Log.d("Select", "" + seletedMenu);

						Intent intent = null;

						switch (seletedMenu) {
						
						//Back to Menu
						case 0:
							intent = new Intent(ReadVisionActivity.this, VisionSoftwareMenuActivity.class);
							startActivity(intent);
						break;
						
						// Read Vision's Plan
						case 1:
							intent = new Intent(ReadVisionActivity.this,
									ReadPlanActivity.class);
							SharedPreferenceUtility.setVisionId(getApplicationContext(), selectedIds);
							startActivity(intent);
							break;
						
						// Create Vision's Plan
						case 2:
							intent = new Intent(ReadVisionActivity.this,
									CreatePlanActivity.class);
							SharedPreferenceUtility.setVisionId(getApplicationContext(), selectedIds);
							startActivity(intent);
							break;

						// Create Vision
						case 3:
							intent = new Intent(ReadVisionActivity.this,
									CreateVisionActivity.class);
							startActivity(intent);
							break;

						// Update Vision
						case 4:
							intent = new Intent(ReadVisionActivity.this,
									UpdateVisionActivity.class);
							intent.putExtra(UXConstants.VISION_ID, selectedIds);
							startActivity(intent);
							break;

						// Delete Vision
						case 5:
							try {
								dao.delete(selectedIds);
								clearData(selectedIds);
							} catch (VisionUpdateException e) {
								e.printStackTrace();
							}
							break;
						}
						
						// Set init value
						seletedMenu = -1;
					}
				});
		
		// Cancel Button
		builder.setNegativeButton(R.string.common_cancel, null);

		// Create Dialog
		menuDialog = builder.create();
		Log.d("Dialog", builder.toString());

		return menuDialog;
	}

	/**
	 * Load List Data
	 * @param selectedIds 
	 */
	private void clearData(int selectedIds) {
		int cnt = visionListLinearLayout.getChildCount();
		Log.i("cnt", "" + cnt);
		
		for (int i = 0 ; i < cnt ; i++) {
			View view = visionListLinearLayout.getChildAt(i);
			Log.i("View", "" + view);
			
			if (view != null && view.getId() == selectedIds) {
				Log.i("Vision Id", "" + view.getId());
				view.setVisibility(View.INVISIBLE);
				view.destroyDrawingCache();
				view.clearAnimation();
				view = null;
			}
		}
	}
	
	/**
	 * Load List Data
	 */
	private void loadData() {
		try {
			// Read All
			list = dao.readAll();
		} catch (VisionReadException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();

		if (dao != null) {
			dao.close();
		}
	}
}